package com.qxy.hgz.rank.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.qxy.hgz.databinding.RecycleViewFragmentBinding;
import com.qxy.hgz.rank.adapter.FilmViewAdapter;
import com.qxy.hgz.rank.model.Variety;
import com.qxy.hgz.util.InitUtil;
import com.qxy.hgz.util.InternetHandler;
import com.qxy.hgz.util.JsonUtil;
import com.qxy.hgz.util.RequestUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Response;

public class varietyFragment extends Fragment {
    private RecycleViewFragmentBinding binding;
    private static RecyclerView recyclerView;
    private static FilmViewAdapter<Variety> adapter;
    private final Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            binding.progressBar.setVisibility(View.GONE);
            if (msg.obj instanceof List) {
                List<Variety> list = (List<Variety>) msg.obj;
                adapter.addListToAdapter(list);
                adapter.notifyDataSetChanged();
            }

        }
    };
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        binding = RecycleViewFragmentBinding.inflate(inflater);
        adapter = new FilmViewAdapter<Variety>(new ArrayList<>());
        InitUtil.initRecycleView(binding.movieRecycleView,adapter,requireActivity());
        RequestUtil.test("https://mpandaer.github.io/tv.json", new InternetHandler() {
            @Override
            public void handleData(Response response) throws IOException, JSONException {
                JSONArray array = JsonUtil.parseListData(new JSONObject(response.body().string()));
                List<Variety> varietyList = null;
                try {
                    varietyList = JsonUtil.getList(array, Variety.class);

                } catch (InvocationTargetException | NoSuchMethodException |
                        IllegalAccessException | java.lang.InstantiationException e) {
                    e.printStackTrace();
                }
                Message message = new Message();
                message.obj = varietyList;
                handler.sendMessage(message);
            }
        });
        return binding.getRoot();
    }
}
